package cn.geodata.tools;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.configuration.XMLConfiguration;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureIterator;

import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Polygon;

public class SearchDatasets {
	private static Logger log = Logger.getAnonymousLogger();
	
	private List<String> layers;
	private Map<String, RasterManager> rasters;
	private XMLConfiguration conf;
	
	public static void main(String[] args) throws IOException {
		SearchDatasets _r = new SearchDatasets();
		_r.retriveTile();
	}
	
	public SearchDatasets() throws IOException {
		conf = Configure.getConfig();
		
		this.layers = Arrays.asList(conf.getStringArray("layers"));
		this.rasters = new HashMap<String, RasterManager>();
		for(String _layer : this.layers){
			log.info("load layer " + _layer);
			this.rasters.put(_layer, new RasterManager(new File(conf.getString(_layer + ".path")), conf.getInt(_layer + ".nodata", 0)));
		}
	}
	
	public List<String> getLayers(){
		return this.layers;
	}
	
	public void retriveTile() throws IOException {
		for(String _layer: this.layers){
			this.retriveTile(_layer);
		}
	}
	
	public void retriveTile(String layer) throws IOException{
		log.info("retrieve layer " + layer);
		FeatureIterator _it = (new TileManager()).getTiles().features();
		File _output = new File(this.conf.getString(layer + ".output"));
		try{
			while(_it.hasNext()){
				Feature _f = _it.next();
				MultiPolygon _multiPoly = (MultiPolygon) _f.getDefaultGeometry();
				Polygon _poly = (Polygon) _multiPoly.getGeometryN(0);
				Polygon _buffer = (Polygon) _poly.buffer(Configure.getConfig().getDouble("distance"));

				int _path = (Integer)_f.getAttribute("PATH");
				int _row = (Integer)_f.getAttribute("ROW");
				
				this.retriveTile(layer, _path, _row, _buffer, _output);
			}
		}
		finally{
			_it.close();
		}
	}
	
	public void retriveTile(String layer, int path, int row, Polygon tile, File output) throws IOException{
		RasterManager _raster = this.rasters.get(layer);
		
		List<RasterInfo> _list = _raster.findDatasets(tile);
		List<String> _datasetNames = new ArrayList<String>();
		for(RasterInfo _r : _list){
			_datasetNames.add(_r.getFile().getName());
		}
		
		DecimalFormat _format = new DecimalFormat("000");
		System.out.println(layer + "p" + _format.format(path) + "r" + _format.format(row) + "=" + Arrays.toString(_datasetNames.toArray(new String[0])));
	}
}
